#!/bin/bash
source ./conf/config.sh

function change_item(){
	local file content num  num_arr
	file=$1
	content=$2
	num_arr=$3
	for num in `echo $num_arr`
	do
		sed -i "${num}c \      $content" $file
	done
}
	

function change_index_syslog(){
        local index_file syslog_file environment region timezone num
        index_file=$1
        environment=$2
        region=$3
        timezone=$4
        syslog_file=$5
	[ "$environment" == "sbpre" -o "$environment" == "sandbox" ] && environment=sandbox
	[ "$environment" == "online" -o "$environment" == "ope" ] && environment=production
        num_language=`cat $index_file |grep -n "^[[:space:]]\{1,\}define.*LANGUAGE"|grep -P -v "^\d+\:\s*\/\/"|awk -F':' '{print $1}'`
        num_environment=`cat $index_file |grep -n "^[[:space:]]\{1,\}define.*ENVIRONMENT"|grep -P -v "^\d+\:\s*\/\/"|awk -F':' '{print $1}'`
        num_index_timezone=`cat $index_file |grep -n "date_default_timezone_set"|grep -P -v "^\d+\:\s*\/\/"|awk -F':' '{print $1}'`
        num_syslog_timezone=`cat $syslog_file|grep -n "date_default_timezone_set"|grep -P -v "^\d+\:\s*\/\/"|awk -F':' '{print $1}'`

        change_item "$index_file" "define('LANGUAGE','$region');" $num_language
        change_item "$index_file" "define('ENVIRONMENT','$environment');" $num_environment
        change_item "$index_file" "date_default_timezone_set('$timezone');" $num_index_timezone
        change_item "$syslog_file" "date_default_timezone_set('$timezone');" $num_syslog_timezone
	
	echo $index_file > /tmp/deploy_list_file
	echo $syslog_file >> /tmp/deploy_list_file
}


function change_config(){
        local config_file region
        config_file=$1
        region=$2
        case $region in
        #       tc)
        #               language='zh-tw'
        #               ;;
                cn)
                        language='zh-cn'
                        ;;
                *)
                        language='english'
                        ;;
        esac
        num_conf_language=`cat $config_file|grep -n "\$config\['language'\]"|grep -P -v "^\d+\:\s*\/\/"|awk -F':' '{print $1}'`
        num_conf_base_url=`cat $config_file|grep -n "\$config\['base_url'\].*"|grep -P -v "^\d+\:\s*\/\/"|awk -F':' '{print $1}'`
        change_item "$config_file" "\$config['language']     = '$language';" "$num_conf_language"
        change_item "$config_file" "\$config['base_url'] = 'http:\/\/'.\$_SERVER\['HTTP_HOST'\]\;" "$num_conf_base_url"
	
	echo $config_file >> /tmp/deploy_list_file
}

function change_region_config(){
	local app env  
	app=$1
	env=$2
	if [ "$env" == "online" -o "$env" == "ope" ]
	then
		env=""
		awsEnable="TRUE"
		awsAccessKey="AKIAJ7IRYRMSUEPLNFIQ"
		awsSecretKey="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"
		awsBucketName="us-kick9"
		upyunEnable="null"
		upyunUsername="null"
		upyunPassword="null"
		upyunBucket="null"
		k9pfSbDsn="mysql://k9pf:k9_01@kick9-sandbox-dbinstance.cecea3qxnwct.us-west-2.rds.amazonaws.com/k9pf"
		k9daSbDsn="mysql://k9da:k9_01@kick9-sandbox-dbinstance.cecea3qxnwct.us-west-2.rds.amazonaws.com/k9da";
		k9paySbDsn="mysql://k9transaction:k9_01@kick9-sandbox-dbinstance.cecea3qxnwct.us-west-2.rds.amazonaws.com/k9transaction"
		k9pushSbDsn="mysql://k9push:k9_01@kick9-sandbox-dbinstance.cecea3qxnwct.us-west-2.rds.amazonaws.com/k9push"
		eval ${app}ResDomain="http://cdn.s3.kick9.com/"
		eval ${app}Domain="http://${app}.kick9.com/"
		eval ${app}CookieDomain="http://${app}.kick9.com/"
	elif [ "$env" == "sandbox" -o "$env" == "sbpre" ]
	then
		env=sb
		awsEnable="TRUE"
		awsAccessKey="AKIAJ7IRYRMSUEPLNFIQ"
		awsSecretKey="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"
		awsBucketName="sb-us-kick9"
		upyunEnable="FALSE"
		upyunUsername="null"
		upyunPassword="null"
		upyunBucket="null"
		k9pfSbDsn="null"
		k9daSbDsn="null"
		k9paySbDsn="null"
		k9pushSbDsn="null"
		eval ${app}ResDomain="https://${awsBucketName}.s3.amazonaws.com/"
		eval ${app}Domain="http://${env}.${app}.kick9.com/"
		eval ${app}CookieDomain="http://${env}.${app}.kick9.com/"
	elif [ "$env" == "dev" ]
	then
		env=dev
		awsEnable="FALSE"
		awsAccessKey="null"
		awsSecretKey="null"
		awsBucketName="null"
		upyunEnable="FALSE"
		upyunUsername="null"
		upyunPassword="null"
		upyunBucket="null"
		k9pfSbDsn="null"
		k9daSbDsn="null"
		k9paySbDsn="null"
		k9pushSbDsn="null"
		eval ${app}ResDomain="https://${awsBucketName}.s3.amazonaws.com/"
		eval ${app}Domain="http://${env}.${app}.kick9.com/"
		eval ${app}CookieDomain="http://${env}.${app}.kick9.com/"
	fi
	uid=300000000000
	eval start_change_region_config "\$${app}Domain" "\$${app}CookieDomain" "\$${app}ResDomain" "$uid" "$awsEnable" "$awsAccessKey" "$awsSecretKey" "$awsBucketName" "$upyunEnable" "$upyunBucket" "$upyunUsername" "$upyunPassword" "$app" "./$app/config/config_${region}.php" "$region" "$k9pfSbDsn" "$k9daSbDsn" "$k9paySbDsn" "$k9pushSbDsn"
}

function start_change_region_config(){
	local domain appdomain  resdomain cookiedomain uid aws_enable aws_access_key aws_secret_key aws_bucket_name dsn_sb_pf dsn_sb_da dsn_sb_transaction dsn_sb_push upyun_enable upyun_bucket upyun_username upyun_password app region file
	appdomain=$1
	cookiedomain=$2
	resdomain=$3
	uid=$4
	aws_enable=$5
	aws_access_key=$6
	aws_secret_key=$7
	aws_bucket_name=$8
	upyun_enable=$9
	upyun_bucket=${10}
	upyun_username=${11}
	upyun_password=${12}
	app=${13}
	file=${14}
	region=${15}
	k9pfSbDsn=${16}
	k9daSbDsn=${17}
	k9paySbDsn=${18}
	k9pushSbDsn=${19}
	for i in `seq 1 19`
	do 
		eval echo \${$i}
	done
	num_config_region_domain=`cat $file|grep -n "config\['domain'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_resdomain=`cat $file|grep -n "config\['res_domain'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_cookiedomain=`cat $file|grep -n "config\['cookie_domain'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_uid=`cat $file|grep -n "config\['uid'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_aws_enable=`cat $file|grep -n "config\['aws_enable'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_aws_access_key=`cat $file|grep -n "config\['aws_access_key'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_aws_secret_key=`cat $file|grep -n "config\['aws_secret_key'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_aws_bucket_name=`cat $file|grep -n "config\['aws_bucket_name'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_upyun_enable=`cat $file|grep -n "config\['upyun_enable'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_upyun_bucket=`cat $file|grep -n "config\['upyun_bucket'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_upyun_username=`cat $file|grep -n "config\['upyun_username'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_upyun_password=`cat $file|grep -n "config\['upyun_password'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_dsn_sb_pf=`cat $file|grep -n "config\['dsn_sb_pf'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_dsn_sb_da=`cat $file|grep -n "config\['dsn_sb_da'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_dsn_sb_transaction=`cat $file|grep -n "config\['dsn_sb_transaction'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	num_config_region_dsn_sb_push=`cat $file|grep -n "config\['dsn_sb_push'\]"|grep "\:\\\\\$"|awk -F':' '{print $1}'`
	[ -n "$num_config_region_domain" ] && change_item "$file" "\$config['domain'] = '$appdomain';"   "$num_config_region_domain"
	[ -n "$num_config_region_domain" ] && change_item "$file" "\$config['cookie_domain'] = '$cookiedomain';" "$num_config_region_cookiedomain"
	[ -n "$num_config_region_resdomain" ] && change_item "$file" "\$config['res_domain'] = '$resdomain';" "$num_config_region_resdomain"
	[ -n "$num_config_region_uid" ] && change_item "$file" "\$config['uid'] = '$uid';" "$num_config_region_uid"
	[ -n "$num_config_region_aws_enable" ] && change_item "$file" "\$config['aws_enable'] = '$aws_enable';" "$num_config_region_aws_enable"
	[ -n "$num_config_region_aws_access_key" ] && change_item "$file" "\$config['aws_access_key'] = '$aws_access_key';" "$num_config_region_aws_access_key"
	[ -n "$num_config_region_aws_secret_key" ] && change_item "$file" "\$config['aws_secret_key'] = '$aws_secret_key';" "$num_config_region_aws_secret_key"
	[ -n "$num_config_region_aws_bucket_name" ] && change_item "$file" "\$config['aws_bucket_name'] = '$aws_bucket_name';" "$num_config_region_aws_bucket_name"
	[ -n "$num_config_region_upyun_enable" ] && change_item "$file" "\$config['upyun_enable'] = '$upyun_enable';" "$num_config_region_upyun_enable"
	[ -n "$num_config_region_upyun_bucket" ] && change_item "$file" "\$config['upyun_bucket'] = '$upyun_bucket';" "$num_config_region_upyun_bucket"
	[ -n "$num_config_region_upyun_username" ] && change_item "$file" "\$config['upyun_username'] = '$upyun_username';" "$num_config_region_upyun_username"
	[ -n "$num_config_region_upyun_password" ] && change_item "$file" "\$config['upyun_password'] = '$upyun_password';" "$num_config_region_upyun_password"
	[ -n "$num_config_region_dsn_sb_pf" ] && change_item "$file" "\$config['dsn_sb_pf'] = '$k9pfSbDsn';" "$num_config_region_dsn_sb_pf"
	[ -n "$num_config_region_dsn_sb_da" ] && change_item "$file" "\$config['dsn_sb_da'] = '$k9daSbDsn';" "$num_config_region_dsn_sb_da"
	[ -n "$num_config_region_dsn_sb_transaction" ] && change_item "$file" "\$config['dsn_sb_transaction'] = '$k9paySbDsn';" "$num_config_region_dsn_sb_transaction"
	[ -n "$num_config_region_dsn_sb_push" ] && change_item "$file" "\$config['dsn_sb_push'] = '$k9pushSbDsn';" "$num_config_region_dsn_sb_push"

	echo ${14} >> /tmp/deploy_list_file
}

function change_db_mem_config(){
	local app env db_confdir mem_confdir
	app=$1
	env=$2
	db_confdir=$3
	mem_confdir=$4
        [ "$env" == "online" -o "$env" == "ope" ] && db_pre=production
        [ "$env" == "sandbox" -o "$env" == "sbpre" ] && db_pre=sandbox
	if [ "$app" != "k9pf" ] 
	then
		rm -f $app/libraries/memcached_lib.php
                ln -s ../../../k9pf/k9pf/libraries/memcached_lib.php $app/libraries/memcached_lib.php
                rm -rf $app/config/${db_pre}
                ln -s ../../../k9pf/k9pf/config/${db_pre} $app/config/${db_pre}
		return
        fi
	if [ -e $db_confdir/${db_pre}_${region}_database.php ]
	then
	 	/bin/cp $db_confdir/${db_pre}_${region}_database.php $app/config/$db_pre/database.php
	else
		echo "=================================>>error:"
		echo "=================================>>error:"
		echo "=================================>>error:"
		echo "no database config file."
		exit
	fi
	if [ "$env" == "ope" ]
	then
		memcachedfile=$mem_confdir/${db_pre}_${region}_memcached_ope.php
	else
		memcachedfile=$mem_confdir/${db_pre}_${region}_memcached.php
	fi
	if [ -e "$memcachedfile" ]
	then
		cp $memcachedfile $app/config/$db_pre/memcached.php
	else
		echo "=================================>>error:"
		echo "=================================>>error:"
		echo "=================================>>error:"
		echo "no $memcachedfile config file."
        fi

	echo $app/libraries/memcached_lib.php >> /tmp/deploy_list_file
	echo $app/config/${env} >> /tmp/deploy_list_file
	echo $app/config/$db_pre/database.php >> /tmp/deploy_list_file
	echo $app/config/$db_pre/database.php >> /tmp/deploy_list_file
	echo $app/config/$db_pre/memcached.php >> /tmp/deploy_list_file
	
}

function merge_helper(){
	local env db_helperdir app
	env=$1
	db_helperdir=$2
	app=$3
	if [ "$env" == "development" -o "$env" == "sbpre" ] 
	then
		cp $db_helperdir/development_db_helper.php $app/helpers/db_helper.php
	else
		cp $db_helperdir/db_helper.php $app/helpers/db_helper.php
	fi
	echo $app/helpers/db_helper.php >> /tmp/deploy_list_file
}
	
function change_dev_link(){
	local app 
	app=$1
        if [ $app == "k9ope" -o $app == "k9cs" ]
        then
                rm $app/models/dev
                ln -s ../../../k9dev/k9dev/models/dev dev
                mv dev $app/models/dev

                rm $app/libraries/dev
                ln -s ../../../k9dev/k9dev/libraries/dev dev
                mv dev $app/libraries/dev

                rm $app/models/da
                ln -s ../../../k9dev/k9dev/models/da da
                mv da $app/models/da
        fi
	echo $app/models/da >> /tmp/deploy_list_file
	echo $app/libraries/dev >> /tmp/deploy_list_file
	echo $app/models/dev >> /tmp/deploy_list_file
}


function rm_extra_file(){
	rm -rf docs
        rm -rf db_schema
        rm -rf user_guide
        rm -rf license.txt mail.html README.md
}

	
function deploy_app_ci(){
	local time_zone app env region commit_rollback des_host last_commit last_commit_time remote_code_dir git_url commit_content git_url_flag app_flag
	app=$1
	env=$2
	region=$3
	commit_rollback=$4
	remote_code_dir=$5
	git_url=$6
	[ "$env" == "online" ] && des_host="kick9_online kick9_online2" || des_host=kick9_$env
	time_zone="America/Los_Angeles"
	if [ "$env" == "sbpre" -o "$env" == "dev" -o "$env" == "sandbox" ]
	then
		branch=development
	elif [ "$env" == "online" -o "$env" == "ope" ]
	then
		branch=master
	else
		echo "=================================>>error:"
		echo "=================================>>error:"
		echo "========================>>$env doesn't exist."
		exit
	fi
	[ -z "$git_url" ] && { echo "git_url is null !";exit ; }
	[ -d "./temp/$app/" ] && cd ./temp/$app/ || { cd ./temp/;git clone $git_url $app;cd $app ;  }
	git reset --hard 
	if [ "$app" == "k9pay" -o "$app" == "k9official" -o "$app" == "k9officialope" ]
	then
		branch=$branch
	fi
	git checkout $branch
	last_commit=`git log --oneline|head -1|awk '{print $1}'`
	echo last_commit $last_commit
	last_commit_time=`date "+%F %T"`
	commit_content=`mysql -h$dbhost -u$db_user -p$password -e "use $dbname;select last_commit from commit_log where last_commit = '$last_commit' and environment = '$env' and app = '$app';"`
	if [ -n "$commit_content" ]
        then
                echo "this commit is already exist."
        else
                `which mysql` -h$dbhost -u$db_user -p$password -e "use $dbname;insert into commit_log(app,environment,last_commit,last_commit_time) values('$app','$env','$last_commit','$last_commit_time');"
        fi
	git_url_flag=`git remote -v |awk '{print $2}'|sed "s/\_//g"`
        app_flag=`echo $app|sed "s/\_//g"`
        echo $git_url_flag|grep $app_flag || { echo "程序目录为空,将手动克隆." ;exit ; }
	git pull
	[ $? != 0 ] && { echo "pull failed!" && exit 6 ; }
#################
### 版本差异 ####
#################
	[ "$commit_rollback" != "null" ] && { git reset $commit_rollback --hard ; [ $? != 0 ] && { echo "error:回滚失败,没有这个版本." && exit 6 ; }; }
        current_commit=`git log --oneline|head -1|awk '{print $1}'`
	[ -d ../../../k9deployshell/views/en/commit_log ] || mkdir -p ../../../k9deployshell/views/en/commit_log
        git diff $last_commit $current_commit > ../../../k9deployshell/views/en/commit_log/${app}_commit_log.txt

#########################
###### 修改配置文件 #####
#########################
	change_index_syslog "./index.php" "$env" "$region" "$time_zone" "./system/libraries/Log.php" 
	change_config "./$app/config/config.php" "$region"
	change_region_config "$app" "$env"  
	change_db_mem_config  "$app" "$env" "$db_confdir" "$mem_confdir"
	merge_helper "$env" "$db_helperdir" "$app"
	change_dev_link "$app"
	rm_extra_file
	echo docs/ > /tmp/deploy_list
	echo k9i >> /tmp/deploy_list
	echo .git/ >> /tmp/deploy_list
	echo res/sdk >> /tmp/deploy_list
	echo logs/ >> /tmp/deploy_list
	echo msg_sys >> /tmp/deploy_list
	
	for host in `echo $des_host`
	do
		rsync  -vlzrtopg  --exclude-from="/tmp/deploy_list" * $host:$remote_code_dir/deploy_test/
	done
	
	rm -f /tmp/deploy_list
	`which mysql` -h$dbhost -u$db_user -p$password -e "use $dbname;update $tb_deploy_task set status=2 where appid='$appid' and status=1;"
}


function deploy_app_nci(){
	local app env git_url nci_db_flag commit_rollback git_url_flag app_flag
	app=$1
	env=$2
	region=$3
	nci_db_flag=$4
	remote_code_dir=$5
	git_url=$6
	des_host=kick9_$env
	[ "$env" == "online" ] && des_host="kick9_online kick9_online2" || des_host=kick9_$env
        [ -z "$git_url" ] && { echo "git_url is null !";exit ; }
        [ -d "./temp/$app/" ] && cd ./temp/$app/ || { cd ./temp/;git clone $git_url $app;cd $app ;  }
        git reset --hard
	if [ "$env" == "sbpre" -o "$env" == "dev" -o "$env" == "sandbox" ]
        then
                branch=development
        else
                branch=master
        fi
        git checkout $branch
        last_commit=`git log --oneline|head -1|awk '{print $1}'`
        last_commit_time=`date "+%F %T"`
	commit_content=`mysql -h$dbhost -u$db_user -p$password -e "use $dbname;select last_commit from commit_log where last_commit = '$last_commit' and environment = '$env' and app = '$app';"`
        if [ -n "$commit_content" ]
        then
                echo "this release is already exist."
        else
                `which mysql` -h$dbhost -u$db_user -p$password -e "use $dbname;insert into commit_log(app,environment,last_commit,last_commit_time) values('$app','$env','$last_commit','$last_commit_time');"
        fi
	git_url_flag=`git remote -v |awk '{print $2}'|sed "s/\_//g"`
        app_flag=`echo $app|sed "s/\_//g"`
        echo $git_url_flag|grep $app_flag || { echo "程序目录为空,将手动克隆." ;exit ; }
        git pull
	[ $? != 0 ] && { echo "pull failed!" && exit 6 ; }
#################
### 版本差异 ####
#################
	[ "$commit_rollback" != "null" ] && { git reset $commit_rollback --hard ; [ $? != 0 ] && { echo "error:回滚失败,没有这个版本." && exit 6 ; }; }
        current_commit=`git log --oneline|head -1|awk '{print $1}'`
	[ -d ../../../k9deployshell/views/en/commit_log ] || mkdir -p ../../../k9deployshell/views/en/commit_log
        git diff $last_commit $current_commit &> ../../../k9deployshell/views/en/commit_log/${app}_commit_log.txt

#########################
###### 修改配置文件 #####
#########################
	if [ "$nci_db_flag" = 'yes' ]
	then
		echo .git > /tmp/deploy_list
		echo cache >> /tmp/deploy_list
		/bin/cp ../../conf/nci_conf/$app/$branch/* .
		if [ "$app" == "k9wiki" ]
		then
			echo images >> /tmp/deploy_list
		fi
		for host in `echo $des_host`
        	do
                	rsync  -vlzrtopg  --exclude-from="/tmp/deploy_list" * $host:$remote_code_dir/deploy_test/
        	done
	else
		echo .git > /tmp/deploy_list
		echo cache >> /tmp/deploy_list
		for host in `echo $des_host`
		do
			rsync  -vlzrtopg  --exclude-from="/tmp/deploy_list" * $host:$remote_code_dir/deploy_test/
		done
	fi
	
	rm -f /tmp/deploy_list	
	
	`which mysql` -h$dbhost -u$db_user -p$password -e "use $dbname;update $tb_deploy_task set status=2 where appid='$appid' and status=1;"
	
	
}

function deploy_nci(){
	local app env git_url nci_db_flag commit_rollback
	app=$1
	env=$2
	git_url=$3
	nci_db_flag=$4
	commit_rollback=$5
	region=us
	remote_code_dir=$remote_dir
        cd $deploydir
        echo "$app" "$env" "$region" "$commit_rollback" "$remote_code_dir" "$git_url" "$nci_db_flag"
	deploy_app_nci "$app" "$env" "$region" "$nci_db_flag" "$remote_code_dir" "$git_url"
}
 
function deploy_ci(){
        local app env commit_reollback git_url remote_code_dir
        app=$1
        env=$2
        git_url=$3
        commit_rollback=$4
        region=us
        remote_code_dir=$remote_dir
        cd $deploydir
        echo "$app" "$env" "$region" "$commit_rollback" "$remote_code_dir" "$git_url"
        deploy_app_ci "$app" "$env" "$region" "$commit_rollback" "$remote_code_dir" "$git_url"
}

###############################################
###### 参数含义  
###### app(k9pf,k9development,k9pay,k9openpf)
###### env(dev,sbpre,sandbox,online,ope)
###### git_url
###### commit_rollback
###### ci_flag 
###### nci_db_flag yes:有数据库;no:没有数据库
###############################################
appid=`mysql -h$dbhost -u$db_user -p$password -e "use $dbname;select id from $table_app where app_name = '$1';"|tail -1`;
[ $# != 6 ] && { echo "参数不够:1: $1 2: $2 3: $3 4: $4 5: $5 6: $6";`which mysql` -h$dbhost -u$db_user -p$password -e "use $dbname;update $tb_deploy_task set status=4 where appid='$appid' and status=0;" ; exit ; }
app_flag=`echo $1|sed "s/\_//g;s/k9//g"`
git_url_flag=`echo $3|sed "s/\_//g;s/k9//g"`
echo $git_url_flag|grep $app_flag
[ $? != 0 ] && { echo "error:$1 和 $3 不对应." ;exit 8; }
if [ "$5" == 'ci' ]
then
        deploy_ci "$1" "$2" "$3" "$4"
else
        deploy_nci "$1" "$2" "$3" "$4" "$6"
fi

